package br.com.android.financas.activities;

import java.io.Serializable;
import java.sql.SQLException;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import br.com.android.financas.R;
import br.com.android.financas.helper.HomeHelper;
import br.com.android.financas.model.Categoria;

import com.larswerkman.colorpicker.ColorPicker;
import com.larswerkman.colorpicker.SVBar;

public class HomeCategoria extends HomeHelper<Categoria> {

	private static final String CLICK_CATEGORIA_ID = "categoriaId";

	private TextView nome;
	private ColorPicker picker;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setTheme(R.style.Sherlock___Theme_Light);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.categoria_screen);
		getActionBar().setDisplayHomeAsUpEnabled(true);

		picker = (ColorPicker) findViewById(R.categoria.cor);
		SVBar svBar = (SVBar) findViewById(R.categoria.svbar);

		picker.addSVBar(svBar);
		Intent intent = getIntent();

		nome = (TextView) findViewById(R.categoria.nome);

		if (intent.getExtras() != null
				&& intent.getExtras().get(CLICK_CATEGORIA_ID) != null) {
			// get
			Integer id = (Integer) intent.getExtras().get(
					CLICK_CATEGORIA_ID);
			setId(id);
			nome.setText(getInstance().getNome());

			picker.setColor(getInstance().getCor());
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.home_categoria, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent;

		switch (item.getItemId()) {
		case android.R.id.home:
			// app icon in action bar clicked; go home
			intent = new Intent(this, Home.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			return true;
		case R.id.menu_save:

			if(!isValid()){
				Toast.makeText(this, R.string.required_fields, Toast.LENGTH_SHORT).show();
				return false;
			}

			try{
			if (getInstance().getId() == null) {
				save();
			} else {
				update();
			}
			}catch(SQLException e){

			}
			finish();

			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public static void callMe(Context c, Serializable id) {
		Intent intent = new Intent(c, HomeCategoria.class);
		intent.putExtra(CLICK_CATEGORIA_ID, id);
		c.startActivity(intent);
	}

}
